<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片目标检测系统</title>
    <style>
        /* 基础样式 */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f0f2f5;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 30px;
        }

        /* 上传区域样式 */
        .upload-box {
            background: white;
            border-radius: 8px;
            padding: 2rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
            margin: 20px 0;
        }
        #fileInput {
            display: none;
        }
        .custom-upload {
            background: #3498db;
            color: white;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            transition: background 0.3s ease;
        }
        .custom-upload:hover {
            background: #2980b9;
        }

        /* 按钮组样式 */
        .button-group {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 15px;
        }
        #startButton {
            background: #27ae60;
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            color: white;
            cursor: pointer;
            transition: background 0.3s ease;
        }
        #startButton:disabled {
            background: #95a5a6;
            cursor: not-allowed;
        }
        #startButton:hover:not(:disabled) {
            background: #219a52;
        }

        /* 图片预览区域 */
        #preview {
            max-width: 100%;
            margin-top: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

        /* 加载提示 */
        .loading {
            display: none;
            color: #666;
            margin-top: 20px;
        }

        /* 检测信息区域样式 */
        .detection-item {
            margin-bottom: 20px;
        }
        .item {
            margin-bottom: 10px;
        }
        .item span {
            margin-right: 10px;
        }

/* AI 问答模块 - 淡色风格 */
#aiPanel {
    width: 100%;
    max-width: 1300px;
    margin: 0 auto 20px auto;
    background: rgba(255, 255, 255, 0.95); /* 白色半透明背景 */
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); /* 更浅的阴影 */
    border: 1px solid #f0f0f0; /* 添加浅灰色边框 */
}

#chatHistory {
    height: 300px;
    overflow-y: auto;
    margin-bottom: 15px;
    background: #fff; /* 纯白背景 */
    padding: 10px;
    border-radius: 6px;
    border: 1px solid #f0f0f0; /* 浅灰边框 */
}

#aiQuestion {
    flex: 1;
    padding: 8px;
    border-radius: 4px;
    border: 1px solid #e0e0e0; /* 浅灰边框 */
    background: #fff; /* 白色背景 */
    color: #333; /* 深灰文字 */
    transition: border-color 0.3s ease;
}

#aiQuestion:focus {
    border-color: #ffb6c1; /* 浅粉色焦点边框 */
    outline: none;
}

.modern-btn {
    padding: 8px 20px;
    background-color: #ffb6c1; /* 浅粉色背景 */
    color: #fff; /* 保持白色文字 */
    border: none;
    border-radius: 6px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.modern-btn:hover {
    background-color: #ff9aa3; /* 稍深的粉色悬停 */
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(255, 182, 193, 0.3); /* 粉色阴影 */
}

.modern-btn:active {
    transform: translateY(0);
    box-shadow: 0 2px 3px rgba(255, 182, 193, 0.2);
}

/* 新增对话气泡样式 */
.answer-item {
    background: #fff5f8; /* 浅粉白背景 */
    border: 1px solid #ffe5eb; /* 浅粉色边框 */
    padding: 12px;
    margin: 8px 0;
    border-radius: 8px;
    color: #666; /* 中灰文字 */
}

        <!--新增ai问答版块-->


        <!--新增聊天样式-->


         /* 聊天消息样式 */
.message {
    margin: 10px;
    padding: 15px;
    border-radius: 8px;
    max-width: 80%;
    animation: fadeIn 0.3s ease-in;
}

.message.user {
    background: #e3f2fd;
    margin-left: auto;
}

.message.ai {
    background: #f5f5f5;
    margin-right: auto;
}

.message.system {
    background: #ffebee;
    color: #b71c1c;
    text-align: center;
}

.message-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 5px;
    font-size: 0.9em;
}

.latency {
    color: #757575;
    font-size: 0.8em;
}

.message-content {
    white-space: pre-wrap;
    line-height: 1.5;
}

/* 加载动画 */
#aiLoading {
    display: none;
    padding: 10px;
    text-align: center;
    color: #666;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}


        <!--新增聊天样式-->


    </style>
</head>
<body>

 <!-- 修改后的HTML结构 -->
<div class="container">
    <h1>图片目标检测系统</h1>
    <div class="upload-box">
        <!-- 文件选择 -->
        <input type="file" id="fileInput" accept="image/jpeg, image/png">
        <label for="fileInput" class="custom-upload">选择图片</label>

        <!-- 操作按钮组 -->
        <div class="button-group">
            <button id="startButton" disabled>开始检测</button>
            <div class="loading" id="loading">检测中...</div>
        </div>
    </div>

    <!-- 图片展示区和结果显示的文字部分 -->
    <div class="result-container">
        <!-- 图片展示区 -->
        <div id="resultContainer">
            <img id="preview" alt="检测结果预览">
            <div id="detectionInfo" style="margin-top: 20px; padding: 10px; background-color: white; border-radius: 8px;">
                <!-- 检测信息显示区域（动态填充） -->
                <!-- 置信度、类别、坐标都动态加载，不使用静态写死的文本 -->
            </div>
        </div>
        </div>
    </div>
</div>


    <!-- AI 问答模块 -->
    <div id="aiPanel">
        <h3 style="color: #ff6b6b; margin-top:0;">AI咨询</h3>
        <div id="chatHistory">
            <div class="answer-item">
                <strong>系统：</strong>
                <span>欢迎使用大语音模型问答系统，请提出您的问题</span>
            </div>
        </div>
        <div style="display: flex; gap:10px;">
            <input type="text" id="aiQuestion" placeholder="请输入问题...">
            <button class="modern-btn" id="sendQuestion">发送</button>
        </div>
        <div id="aiLoading" style="color: #7f8c8d; display:none; margin-top:5px;">thinking...</div>
    </div>









    <script>
        // DOM元素引用
        const fileInput = document.getElementById('fileInput');
        const startButton = document.getElementById('startButton');
        const preview = document.getElementById('preview');
        const loading = document.getElementById('loading');
        let selectedFile = null;

        // 文件选择事件
        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (!file) return;

            // 文件类型验证
            if (!['image/jpeg', 'image/png'].includes(file.type)) {
                alert('仅支持JPEG/PNG格式');
                return;
            }

            // 显示预览
            const reader = new FileReader();
            reader.onload = (e) => {
                preview.src = e.target.result;
                selectedFile = file;
                startButton.disabled = false;
            }
            reader.readAsDataURL(file);
        });

        // 开始检测按钮点击事件
        startButton.addEventListener('click', async () => {
            if (!selectedFile) return;
            loading.style.display = 'block';
            startButton.disabled = true;

            try {
                const formData = new FormData();
                formData.append('file', selectedFile);
                const response = await fetch('/detect/image', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) throw new Error(`检测失败: ${response.status}`);
                const data = await response.json();

                // 更新图片显示
                preview.src = data.result;

                // 更新检测信息显示
                const detectionInfoDiv = document.getElementById('detectionInfo');
                detectionInfoDiv.innerHTML = ''; // 清空刷新旧内容

                if (data.detection_info && data.detection_info.length > 0) {
                    // 遍历每个检测目标
                    data.detection_info.forEach((item, index) => {
                        const infoContent = document.createElement('div');
                        infoContent.className = 'detection-item';
                        infoContent.innerHTML = `
                            <h4>目标 ${index + 1}</h4>
                            <div class="item">
                                <span>置信度:</span>
                                <span>${item.confidence * 100}%</span>
                            </div>
                            <div class="item">
                                <span>类别:</span>
                                <span>${item.class_id}</span>
                            </div>
                            <div class="item">
                                <span>位置:</span>
                            </div>
                            <div class="item">
                                <span>left:</span>
                                <span>${item.position.left}</span>
                                <span>top:</span>
                                <span>${item.position .top}</span>
                                <br>
                                <span>right:</span>
                                <span>${item.position.right}</span>
                                <span>bottom:</span>
                                <span>${item.position .bottom}</span>
                            </div>
                        `;
                        detectionInfoDiv.appendChild(infoContent);
                    });
                } else {
                    detectionInfoDiv.innerHTML = '未检测到任何目标';
                }

            } catch (error) {
                alert(error.message);
            } finally {
                loading.style.display = 'none';
                startButton.disabled = false;
            }
        });



// AI问答功能实现
const chatHistory = document.getElementById('chatHistory');
const aiQuestion = document.getElementById('aiQuestion');
const sendButton = document.getElementById('sendQuestion');
const aiLoading = document.getElementById('aiLoading');

// 发送问题事件处理
sendButton.addEventListener('click', async () => {
    const question = aiQuestion.value.trim();
    if (!question) return;

    // 禁用输入防止重复提交
    aiQuestion.disabled = true;
    sendButton.disabled = true;
    aiLoading.style.display = 'block';

    try {
        // 添加用户消息（立即显示）
        addMessage(question, 'user');
        aiQuestion.value = '';  // 清空输入框

        // 构造请求数据
        const response = await fetch('/api/ask', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                question: question,
                max_length: 1024,
                temperature: 0.7
            })
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.detail || `请求失败: ${response.status}`);
        }

        const data = await response.json();
        // 添加AI响应
        addMessage(data.answer, 'ai', data.latency);

    } catch (error) {
        // 显示错误消息
        addMessage(`错误: ${error.message}`, 'system');
    } finally {
        // 恢复界面状态
        aiQuestion.disabled = false;
        sendButton.disabled = false;
        aiLoading.style.display = 'none';
        aiQuestion.focus();
    }
});

// 添加消息到聊天历史（新增latency参数）
function addMessage(content, sender, latency) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${sender}`;

    // 构造消息内容
    let htmlContent = `
        <div class="message-header">
            <strong>${sender === 'user' ? '您' : 'AI'}</strong>
            ${sender === 'ai' ? `<span class="latency">${latency?.toFixed(2)}秒</span>` : ''}
        </div>
        <div class="message-content">${content}</div>
    `;

    messageDiv.innerHTML = htmlContent;
    chatHistory.appendChild(messageDiv);

    // 自动滚动到底部（带平滑动画）
    chatHistory.scrollTo({
        top: chatHistory.scrollHeight,
        behavior: 'smooth'
    });
}

// 增强的输入处理
aiQuestion.addEventListener('keydown', (e) => {
    // Shift+Enter换行，单独Enter发送
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        if (!sendButton.disabled) {
            sendButton.click();
        }
    }

    // 自动扩展文本框
    if (e.target.scrollHeight > e.target.clientHeight) {
        e.target.style.height = e.target.scrollHeight + 'px';
    }
});


    </script>



</body>
</html>
